package io.kiki.sba.registry.client.provider;

import io.kiki.sba.registry.client.remoting.Server;
import io.kiki.sba.registry.client.util.StringUtils;
import lombok.Getter;
import lombok.Setter;

import java.util.Properties;

@Setter
@Getter
public class ServerImpl implements Server {

    private static final String WEIGHT_KEY = "weight";
    private String url;
    private String host;
    private int port;
    private Properties properties;


    public ServerImpl(String url, String host, int port, Properties properties) {
        this.url = url;
        this.host = host;
        this.port = port;
        this.properties = properties;
    }


    @Override
    public String getHost() {
        return host;
    }


    @Override
    public int getPort() {
        return port;
    }


    @Override
    public String getUrl() {
        return url;
    }

    @Override
    public int getWeight() {
        if (null == getProperties()) {
            return 0;
        }
        String weightStr = getProperties().getProperty(WEIGHT_KEY);
        if (StringUtils.isBlank(weightStr)) {
            return 0;
        }
        try {
            return Integer.parseInt(weightStr);
        } catch (NumberFormatException e) {
            return 0;
        }
    }


    @Override
    public Properties getProperties() {
        return properties;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof ServerImpl)) {
            return false;
        }

        ServerImpl that = (ServerImpl) o;

        if (port != that.port) {
            return false;
        }
        if (url != null ? !url.equals(that.url) : that.url != null) {
            return false;
        }
        if (host != null ? !host.equals(that.host) : that.host != null) {
            return false;
        }
        return properties != null ? properties.equals(that.properties) : that.properties == null;
    }


    @Override
    public int hashCode() {
        int result = url != null ? url.hashCode() : 0;
        result = 31 * result + (host != null ? host.hashCode() : 0);
        result = 31 * result + port;
        result = 31 * result + (properties != null ? properties.hashCode() : 0);
        return result;
    }


}
